package com.chencs.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chencs.vo.biz.password.QinTao;
import com.chencs.vo.biz.product.CmdModel;
import com.chencs.vo.biz.product.ProductModel;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;


public class GetTmailUrl {

	public static String getOne(String url){

		  //构造HttpClient的实例 
		  HttpClient httpClient = new HttpClient();
		  //创建GET方法的实例 
		  GetMethod getMethod = new GetMethod(url);
		  //使用系统提供的默认的恢复策略 
		  getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
		    new DefaultHttpMethodRetryHandler());
		  try {
		   //执行getMethod 
		   int statusCode = httpClient.executeMethod(getMethod); 
		   if (statusCode != HttpStatus.SC_OK) {
		   } 
		   //读取内容 
		   byte[] responseBody = getMethod.getResponseBody(); 
		   //处理内容 
		  	return new String(responseBody,"utf-8");
		  } catch (HttpException e) {
		 
		   //发生致命的异常，可能是协议不对或者返回的内容有问题 
		   e.printStackTrace(); 
		  } catch (IOException e) { 
		   //发生网络异常 
		   e.printStackTrace(); 
		  } finally { 
		   //释放连接 
		   getMethod.releaseConnection(); 
		  }
		return "-1"; 
		 
	}
	
	public static String getTow(String url){
		  //构造HttpClient的实例 
		  HttpClient httpClient = new HttpClient(); 
		  //创建GET方法的实例 
		  GetMethod getMethod = new GetMethod(url); 
		  //使用系统提供的默认的恢复策略 
		  getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
		    new DefaultHttpMethodRetryHandler()); 
		  try {
		   //执行getMethod 
		   int statusCode = httpClient.executeMethod(getMethod); 
		   if (statusCode != HttpStatus.SC_OK) {
		   }
		  	return getMethod.getURI().toString();
		  } catch (HttpException e) { 
		 
		   //发生致命的异常，可能是协议不对或者返回的内容有问题 
		   e.printStackTrace(); 
		  } catch (IOException e) { 
		   //发生网络异常 
		   e.printStackTrace(); 
		  } finally { 
		   //释放连接 
		   getMethod.releaseConnection(); 
		  }
		return "-1"; 
		 
	}
	

	public static String getCode(String strHtml){
		String txtcontent = "http"+ strHtml.split("http")[1].split("\\)")[0];
         return txtcontent;
	}


	/**
	 * 淘口令地址解析后拿到sellerId ID 信息之类
	 * @param code
	 * @return
	 */
	public static String getTaboSellerId(String code,ProductModel model){


		String one1 = getOne("http://pub.alimama.com/items/search.json?q="+code);
		JSONObject gs  = JSONObject.parseObject(one1);
		JSONObject data = JSONObject.parseObject(gs.getString("data"));
		JSONArray jArray = JSONArray.parseArray(data.getString("pageList"));
		String sid ="-1";
		try {
			 sid =  JSONObject.parseObject(jArray.get(0).toString()).getString("sellerId");
			 model.setSellerid(sid);
		//	System.out.println("---"+jArray.get(0).toString());
			if (model.getPrice()==null){
				model.setPrice(JSONObject.parseObject(jArray.get(0).toString()).getString("zkPrice"));
			}
			 model.setCounpurl("http://h5.m.taobao.com/jxt/coupon-tb.html?sellerId="+sid+"&itemId="+model.getPid()+"");
			model.setList(getHideCounp(sid,model.getPid()));
		}catch (Exception e){
			e.printStackTrace();
		}
		return  sid;
	}

	public static ProductModel getTmallProductTitle(String code){
		ProductModel model = new ProductModel();
		String url = getCode(code);
		String one = getOne(url);
	//	System.out.println("one:："+one);
		String baseUrl = one.replace(" ", "").split("varpageData=")[1].split("</script>")[0].replace(";", "");
		JSONObject base  = JSONObject.parseObject(baseUrl);
		JSONArray baseList = JSONArray.parseArray(base.getString("actionRule"));
		String newUrl =JSONObject.parseObject(baseList.get(0).toString()).getString("url");
	//	System.out.println("newUrl:："+(newUrl.indexOf("http")==-1?"http:"+newUrl:newUrl));
		String finalUrl = getTow(newUrl.indexOf("http")==-1?"http:"+newUrl:newUrl);
		String one1 = getOne("http://pub.alimama.com/items/search.json?q="+getTow(finalUrl));
		JSONObject gs  = JSONObject.parseObject(one1);
		JSONObject data = JSONObject.parseObject(gs.getString("data"));
		JSONArray jArray = JSONArray.parseArray(data.getString("pageList"));
		if(jArray!=null){
			String title = JSONObject.parseObject(jArray.get(0).toString()).getString("title");
			String zkPrice = JSONObject.parseObject(jArray.get(0).toString()).getString("zkPrice");
			String pric ="http:"+JSONObject.parseObject(jArray.get(0).toString()).getString("pictUrl");
			String pid = base.getString("bizId");
			String sid =  JSONObject.parseObject(jArray.get(0).toString()).getString("sellerId");
			model.setProurl(finalUrl);
			model.setProimg(pric);
			model.setPname(title);
			model.setPrice(zkPrice);
			model.setPid(pid);
			model.setSellerid(sid);
			model.setCounpurl("http://h5.m.taobao.com/jxt/coupon-tb.html?sellerId="+model.getSellerid()+"&itemId="+model.getPid()+"");
			model.setList(getHideCounp(model.getSellerid(),model.getPid()));
		}else{
			String title = base.getString("content");
			model.setPrice(base.getString("itemPrice"));
			String pric ="http:"+JSONObject.parseObject(base.getString("backgroundImg")).getString("m");
			String pid = base.getString("bizId");
		//	String sid =  JSONObject.parseObject(jArray.get(0).toString()).getString("sellerId");
			model.setProurl(finalUrl);
			model.setProimg(pric);
			model.setPname(title);
		//	model.setPrice(zkPrice+"");
			model.setPid(pid);

		}


		return  model;
	}


	/**
	 * 拿倒券信息
	 * @param sid
	 * @param gid
	 * @return
	 */
	public static List<QinTao> getHideCounp(String sid,String gid) {
		String string = HttpPostGiftCode.QingTaoKe(sid, gid);
		JSONObject base = JSONObject.parseObject(string);
		JSONArray baseList = JSONArray.parseArray(base.getString("data"));
		List<QinTao> qinTaoList = new ArrayList<>();
		QinTao qinTao;
		try {
			for (int i = 0; i < baseList.size(); i++) {
				qinTao = new QinTao();
				String aid = JSONObject.parseObject(baseList.get(i).toString()).getString("activityId");
				String str = HttpPostGiftCode.getPwdInfo(aid, gid);
				JSONObject info = JSONObject.parseObject(str).getJSONObject("result");
				String startFee = info.getString("startFee");
				String amount = info.getString("amount");
				String starttime = info.getString("effectiveStartTime");
				String endtime = info.getString("effectiveEndTime");
				qinTao.setInfo("满" + startFee + "减" + amount);
				qinTao.setPrice(amount);
//				qinTao.setStartime(starttime);
//				qinTao.setEndtime(endtime);
				qinTao.setUrl("https://uland.taobao.com/coupon/edetail?activityId=" + aid + "&src=tkdg_tkdggj&pid=mm_16510629_18916799_68766966&itemId=" + gid);
			//	System.out.println(JSON.toJSONString(qinTao));
				if(startFee!=null){
					qinTaoList.add(qinTao);
				}
			}
		}catch (Exception e){
			return  null;
		}
	 return  qinTaoList;
	}


//
//	public static void main(String[] args) {
//		GetTmailUrl dGetTmailUrl = new GetTmailUrl();
//		String url = dGetTmailUrl.getCode("复制整段信息，打开天猫APP，即可查看此商品:【HSTYLE/韩都衣舍 韩版女装宽松连帽无袖印花连衣裙2017夏季新款】(未安装App点这里：http://zmnxbc.com/s/G3uhg?tm=c4920a )喵口令");
//		String one = dGetTmailUrl.getOne(url);
//		String baseUrl = one.replace(" ", "").split("varpageData=")[1].split("</script>")[0].replace(";", "");
//		JSONObject base  = JSONObject.parseObject(baseUrl);
//		JSONArray baseList = JSONArray.parseArray(base.getString("actionRule"));
//
//		//String newUrl ="https:"+JSONObject.parseObject(baseList.get(0).toString()).getString("url");
//		String newUrl = "http://item.taobao.com/item.htm?id=529404594645";
//		String one1 = dGetTmailUrl.getOne("http://pub.alimama.com/items/search.json?q="+newUrl);
//		System.out.println(one1);
//		JSONObject gs  = JSONObject.parseObject(one1);
//		JSONObject data = JSONObject.parseObject(gs.getString("data"));
//		JSONArray jArray = JSONArray.parseArray(data.getString("pageList"));
//		System.out.println(JSONObject.parseObject(jArray.get(0).toString()).getString("title"));
//		System.out.println(JSONObject.parseObject(jArray.get(0).toString()).getString("sellerId"));
//		System.out.println(JSONObject.parseObject(jArray.get(0).toString()).getString("auctionId"));
//	//	dGetTmailUrl.getCode("复制整段信息，打开天猫APP，即可查看此商品:【湔韩都衣舍2017韩版女装冬装新款拼接宽松显瘦毛领棉衣DQ8459堯】(未安装App点这里：http://zmnxbc.com/s/gUI8h?tm=63affe )喵口令");
//	//	String string =  HttpPostGiftCode.QingTaoKe(JSONObject.parseObject(jArray.get(0).toString()).getString("sellerId"),JSONObject.parseObject(jArray.get(0).toString()).getString("auctionId"));
//		String string =  HttpPostGiftCode.QingTaoKe("763968012","40318990049");
//		JSONObject base  = JSONObject.parseObject(string);
//		JSONArray baseList = JSONArray.parseArray(base.getString("data"));
//
//		QinTao qinTao;
//		String gid = "40318990049";
//		for(int i =0;i<baseList.size();i++){
//			qinTao = new QinTao();
//			String aid = JSONObject.parseObject(baseList.get(i).toString()).getString("activityId");
//			String str = HttpPostGiftCode.getPwdInfo(aid,gid);
//			JSONObject info  = JSONObject.parseObject(str).getJSONObject("result");
//			String startFee = info.getString("startFee");
//			String amount = info.getString("amount");
//			String starttime = info.getString("effectiveStartTime");
//			String endtime = info.getString("effectiveEndTime");
//			qinTao.setInfo("满"+startFee+"减"+amount);
//			qinTao.setPrice(amount);
//			qinTao.setStartime(starttime);
//			qinTao.setEndtime(endtime);
//			qinTao.setUrl("https://uland.taobao.com/coupon/edetail?activityId="+aid+"&src=tkdg_tkdggj&pid=mm_16510629_18916799_68766966&itemId="+gid);
//		String code = HttpPostGiftCode.http2("￥pni40UrTV6j￥");
//		System.out.println(code);
//		JSONObject xbs  = JSONObject.parseObject(code);
//		CmdModel cmdModel = JSON.parseObject(xbs.getString("data"),CmdModel.class);
//		System.out.println();
//		System.out.println(JSON.toJSONString(cmdModel));



//		Connection connection = Jsoup.connect("https://api.huiwancun.net/HwcWxappService/taobaoapp/parseProduct.api");
//		connection.data("aaa","ccc");  // 这是重点
//		connection.header("Content-Type", "application/json; charset=UTF-8");  // 这是重点
//		connection.header("Accept", "text/plain, */*; q=0.01");
//		connection.timeout(15000);
//		String body = "{\"content\":\"44CQ5oiR5YmB5omL6YO96KaB5Lmw55qE5a6d6LSd77yI6IuP5rOK5bCU55S154Gr6ZSF54Ot6ZSF5rau6ZSF55S154Wu6ZSF5aSa5Yqf6IO95a6255So5LiN57KY6ZSF6Z+p5byP5rau6IKJ6ZSF5q2j5ZOB77yJ77yM5b+r5p2l5ZKM5oiR5LiA6LW355Oc5YiG57qiSeWMheOAkWh0dHA6Ly92LmN2ejUuY29tL2gudUhTTTBLIOeCueWHu+mTvuaOpe+8jOWGjemAieaLqea1j+iniOWZqOaJk+W8gO+8m+aIluWkjeWItui/meadoeS/oeaBr++/pXNDYnkwZ1g4VDRk77+l5ZCO5omT5byA5omL5reY\"}";
//		connection.postDataCharset(body);

//		String requestStr = "{\"content\":\"44CQ5oiR5YmB5omL6YO96KaB5Lmw55qE5a6d6LSd77yI6IuP5rOK5bCU55S154Gr6ZSF54Ot6ZSF5rau6ZSF55S154Wu6ZSF5aSa5Yqf6IO95a6255So5LiN57KY6ZSF6Z+p5byP5rau6IKJ6ZSF5q2j5ZOB77yJ77yM5b+r5p2l5ZKM5oiR5LiA6LW355Oc5YiG57qiSeWMheOAkWh0dHA6Ly92LmN2ejUuY29tL2gudUhTTTBLIOeCueWHu+mTvuaOpe+8jOWGjemAieaLqea1j+iniOWZqOaJk+W8gO+8m+aIluWkjeWItui/meadoeS/oeaBr++/pXNDYnkwZ1g4VDRk77+l5ZCO5omT5byA5omL5reY\"}";


	//	String requestStr = "{\"content\":\"44CQ5oiR5YmB5omL6YO96KaB5Lmw55qE5a6d6LSd77yI6aOe56eR5YmD6aG75YiA5YWo6Lqr5rC05rSX6aOe56eR55S15Yqo5YmD6aG75YiA55S35aOr5Yiu6IOh5YiA5YWF55S15byP6IOh6aG75YiARlMzNzPvvInvvIzlv6vmnaXlkozmiJHkuIDotbfnk5zliIbnuqLljIXjgJFodHRwOiAvL3YuY3Z6NS5jb20vaC5HaUw3SnPngrnlh7vpk77mjqXvvIzlho3pgInmi6nmtY/op4jlmajmiZPlvIDvvJvmiJblpI3liLbov5nmnaHkv6Hmga/vv6VmczJ1MFVxS0RsVe+/peWQjuaJk+W8gOaJi+acuua3mOWunWY=\"}";
		//构造HttpClient的实例

		//创建GET方法的实例
//		try{
//			PostMethod getMethod = new PostMethod("https://api.huiwancun.net/HwcWxappService/taobaoapp/parseProduct.api");
//			RequestEntity entity = new StringRequestEntity(requestStr,"application/json","UTF-8");
//			getMethod.setRequestEntity(entity);
//			getMethod.setRequestHeader("Content-Type","application/json;charset=UTF-8");
//			new HttpClient().executeMethod(getMethod);
//			InputStream inputStream = getMethod.getResponseBodyAsStream();
//			BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
//			StringBuffer stringBuffer = new StringBuffer();
//			String str= "";
//			while((str = br.readLine()) != null){
//				stringBuffer .append(str);
//			}
//			String str2 = stringBuffer.toString();
//			System.out.println(str2);
//			Boolean flag  = JSONObject.parseObject(str2).getBoolean("success");
//			if (flag) {
//				JSONObject base  = JSONObject.parseObject(str2).getJSONObject("product");
//				JSONArray baseList = JSONArray.parseArray(base.getString("coupons"));
//				List<QinTao> qinTaoList = new ArrayList<>();
//				QinTao qinTao;
//				for(int i=0;i<baseList.size();i++){
//					qinTao = new QinTao();
//					String amount = baseList.getJSONObject(i).getString("amount");
//					qinTao.setInfo(baseList.getJSONObject(i).getString("applyAmountTxt"));
//					qinTao.setPrice(amount);
//					qinTao.setStartime("");
//					qinTao.setEndtime("");
//					//System.out.println(baseList.getJSONObject(i).getString("urlpath"));
//					//System.out.println(StringUtils.repcUrl(baseList.getJSONObject(i).getString("urlpath")));
//					qinTao.setUrl(StringUtils.repcUrl(baseList.getJSONObject(i).getString("urlpath")));
//					qinTaoList.add(qinTao);
//				}
//				ProductModel model = new ProductModel();
//				model.setProurl(base.getString("urlpath"));
//				model.setProimg(base.getString("pic_url"));
//				model.setPname(base.getString("title"));
//				model.setPrice(base.getString("price"));
//				model.setPid(base.getString("open_id"));
//				model.setSellerid(base.getString("sellerid"));
//				model.setCounpurl("http://h5.m.taobao.com/jxt/coupon-tb.html?sellerId="+model.getSellerid()+"&itemId="+model.getPid()+"");
//				model.setList(qinTaoList);
//
//			}else{
//				System.out.println("失败");
//			}
//
//
//
//		}catch (Exception e){
//			e.printStackTrace();
//		}
//
////
//		}


//		System.out.println(string);
//}




}
